import axios, { AxiosRequestConfig, AxiosResponse, AxiosError } from 'axios'
import toast from 'react-hot-toast';

export interface TResData<T> {
    data: T,
    msg?: string
    code?: number
}

const getBaseUrl = () => {
    switch (process.env.CLIENT_ENV) {
        case 'local':
            return '/api'
        case 'proxy':
        case 'prod':
            return '/api/v1'
    }
}


const axiosInstance = axios.create({
    baseURL: getBaseUrl(),
    timeout: 1000,
    headers: { 'Authorization': 'Bearer ' + localStorage.getItem('token') },
});

type extendRequsetConfig = {
    data?: any,
    success?: (res: any) => void,
    error?: (err: any) => void,
    showError?: boolean,
    showSuccess?: boolean,
}

const defaultConfig: extendRequsetConfig = {
    showError: true,
    showSuccess: false
}

const request = <T>(url: string, config?: extendRequsetConfig & AxiosRequestConfig) => {
    const _config = {
        ...defaultConfig,
        ...config
    }
    const { data, params } = _config
    const method = _config.method || 'get'



    return axiosInstance.request({
        url,
        method: process.env.CLIENT_ENV === 'local' ? 'get' : method,
        data: data || {},
        params: params || {},
    }).then((res: AxiosResponse) => {
        const data = res.data;
        _config.success && _config.success(data);
        if (_config.showSuccess) toast.success(data.msg || '请求成功');
        return data as TResData<T>
    }).catch((err) => {
        if (err.response.status >= 500) {
            toast.error('服务器发生错误，请稍后再试')
            throw new Error('服务器发生错误，请稍后再试')
        }
        if (err.response.status === 401) {
            toast.error('用户凭证出现问题，请重新登录')
            location.href = '/login'
            throw new Error('用户凭证出现问题，请重新登录')
        }
        let data = err.response.data
        _config.error && _config.error(data)
        if (_config.showError) toast.error(data.msg || '未知错误')

        return data
    })
}


export default request